//
//  UrlUtil.swift
//  browser
//
//  Created by Kotori on 2021/6/11.
//

import Foundation
import UIKit

// 匹配URL是否有效正则表达式，允许域名和IP，不检测顶级域名的有效性
let validPattern = "^((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)+(([a-zA-Z0-9._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(/[a-zA-Z0-9&%_\\./-~-]*)?$"
let regex = try? NSRegularExpression(pattern: validPattern, options: [])


class UrlUtil {
    static let searchEngineList: [SearchEngine] = SearchEngine.searchEngineList()
    
    static func getVaildHttpUrl(url: String) -> String {
        if let results = regex?.matches(in: url, options: [], range: NSRange(location: 0, length: url.count)), results.count != 0 {
            return url
        }
        //加上https协议头再次匹配
        let modifyUrl = "https://" + url
        if let results = regex?.matches(in: modifyUrl, options: [], range: NSRange(location: 0, length: modifyUrl.count)), results.count != 0 {
            return modifyUrl
        }
        //非域名调用搜索引擎，对中文和特殊字符重编码为URL合法格式
        return searchEngineList[UserManager.currUserMgr.getSearchEngineSelectIndex()].searchPrefix + url.addingPercentEncoding(withAllowedCharacters: .urlUserAllowed)!
    }
}
